package io.gitee.hfl.rocketmq.config;

import io.gitee.hfl.rocketmq.handler.ISendCallbackHandler;
import io.gitee.hfl.rocketmq.handler.impl.DefaultSendCallbackHandler;
import io.gitee.hfl.rocketmq.props.RocketProperties;
import io.gitee.hfl.rocketmq.register.ConsumerAutoRegister;
import io.gitee.hfl.rocketmq.resolver.PropertyResolver;
import org.apache.rocketmq.client.apis.*;
import org.apache.rocketmq.shaded.commons.lang3.StringUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

/**
 * rocket-client 自动配置
 *
 * @author hefulin
 * @date 2022/09/07 10:24
 */
@Configuration
@Import({ConsumerAutoRegister.class})
@ConditionalOnProperty(prefix = "rocket", value = "enable")
@EnableConfigurationProperties(RocketProperties.class)
@ConditionalOnClass({ClientConfiguration.class, ClientServiceProvider.class})
public class RocketAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean(ClientServiceProvider.class)
    public ClientServiceProvider clientServiceProvider() {
        return ClientServiceProvider.loadService();
    }

    @Bean
    @ConditionalOnMissingBean(ClientConfiguration.class)
    public ClientConfiguration clientConfiguration(RocketProperties rocketProperties) {
        ClientConfigurationBuilder builder = ClientConfiguration.newBuilder().setEndpoints(rocketProperties.getAddress());
        if (!StringUtils.isBlank(rocketProperties.getAccessKey()) && !StringUtils.isBlank(rocketProperties.getSecretKey())) {
            builder.setCredentialProvider(new StaticSessionCredentialsProvider(rocketProperties.getAccessKey(), rocketProperties.getSecretKey()));
        }
        return builder.build();
    }

    @Bean
    @ConditionalOnMissingBean(ConsumerAutoRegister.class)
    public ConsumerAutoRegister consumerAutoRegister(RocketProperties rocketProperties,
                                                     ApplicationContext applicationContext,
                                                     PropertyResolver propertyResolver,
                                                     ClientConfiguration clientConfiguration,
                                                     ClientServiceProvider clientServiceProvider) {
        return new ConsumerAutoRegister(rocketProperties, applicationContext, propertyResolver, clientConfiguration, clientServiceProvider);
    }

    @Bean
    @ConditionalOnMissingBean(ISendCallbackHandler.class)
    public ISendCallbackHandler sendCallbackHandler() {
        return new DefaultSendCallbackHandler();
    }

}
